package com.ygqh.baby.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ygqh.baby.ao.*;
import com.ygqh.baby.constant.RedisConstant;
import com.ygqh.baby.handler.ShoppingCarHandler;
import com.ygqh.baby.mapper.YgCouponMapper;
import com.ygqh.baby.model.*;
import com.ygqh.baby.po.*;
import com.ygqh.baby.redis.RedisDao;
import com.ygqh.baby.service.*;
import com.ygqh.baby.utils.DateConvertUtils;
import com.ygqh.baby.utils.YgStringUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class YgCouponServiceImpl implements YgCouponService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private YgCouponMapper ygCouponMapper;
    @Autowired
    private YgCouponDetailService couponDetailService;
    @Autowired
    private DocumentConstant documentConstant;
    @Autowired
    private YgProductService ygProductService;
    @Autowired
    private RedisDao redisDao;
    @Autowired
    private ShoppingCarHandler shoppingCarHandler;
    @Autowired
    private YgCouponMemberService ygCouponMemberService;
    @Autowired
    private YgBrandService ygBrandService;

    @Override
    public List<YgCoupon> find(Long supplierId, PromotionStatus pStatus, Date startDate, Date endDate, String q) {
        return ygCouponMapper.selectSuper(null, supplierId, pStatus.name(), startDate, endDate, q, null, null);
    }

    @Override
    public int findCount(Long supplierId) {
        YgCouponExample example = new YgCouponExample();
        example.createCriteria().andStatusNotEqualTo(DataStatus.Delete.name());
        return ygCouponMapper.countByExample(example);
    }

    @Override
    public YgCoupon findById(Long id) {
        String key = String.format(RedisConstant.COUPON_PREFIX, id);
        String string = redisDao.get(key);
        YgCoupon coupon = null;
        if (StringUtils.isEmpty(string)) {
            coupon = ygCouponMapper.selectByPrimaryKey(id);
            if (coupon != null && !SceneType.ALL.equals(coupon.getSceneType())) {
                List<YgCouponMember> memberList = ygCouponMemberService.findMemberList(id, coupon.getSceneType());
                List<Long> collect = memberList.stream().map(YgCouponMember::getRelateId).collect(Collectors.toList());
                coupon.setRelateIdList(collect);
            }
            redisDao.set(key, JSON.toJSONString(coupon), 5 * 60 * 1000);
        } else {
            coupon = JSON.parseObject(string, YgCoupon.class);
        }
        return coupon;
    }

    @Override
    public ResultSet<YgCoupon> search(QueryInfo queryInfo, Long supplierId, PromotionStatus pStatus, Date startDate, Date endDate, String q) {
        int count = ygCouponMapper.countSuper(supplierId, pStatus == null ? null : pStatus.name(), startDate, endDate, q, null, null);
        List<YgCoupon> list = null;
        if (count > 0) {
            list = ygCouponMapper.selectSuper(queryInfo, supplierId, pStatus == null ? null : pStatus.name(), startDate, endDate, q, null, null);
        } else {
            list = Collections.emptyList();
        }
        ResultSet<YgCoupon> resultSet = new ResultSet<YgCoupon>(count, list);
        return resultSet;
    }

    @Override
    public int deleteSoft(Long[] ids) {
        Assert.notEmpty(ids);

        YgCouponExample example = new YgCouponExample();
        example.createCriteria().andIdIn(Arrays.asList(ids));
        YgCoupon record = new YgCoupon();
        record.setStatus(DataStatus.Delete);

        return ygCouponMapper.updateByExampleSelective(record, example);
    }

    @Override
    public int deleteSoft(Long id) {
        return this.deleteSoft(new Long[]{id});
    }

    @Override
    public List<YgCouponModel> findOwnCouponList(QueryInfo queryInfo, Long userId, CouponStatus cStatus, SceneType sceneType, SalesPlatform salesPlatform) {
        List<YgCouponModel> ygCouponModels = ygCouponMapper.selectOwnCouponList(queryInfo, userId, cStatus.name(), DateConvertUtils.format(new Date()),
                sceneType == null ? null : sceneType.name(), salesPlatform == null ? null : salesPlatform.name());
        setBrandInfo(ygCouponModels);
        return ygCouponModels;
    }

    private void setBrandInfo(List<YgCouponModel> ygCouponModels) {
        List<YgCouponModel> brandCouponList = ygCouponModels.stream().filter(coupon -> SceneType.Brand.equals(coupon.getSceneType())).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(brandCouponList)) {
            List<Long> brandIdList = brandCouponList.stream().flatMap(ygCouponModel -> ygCouponModel.getRelateIdList().stream()).collect(Collectors.toList());
            List<YgBrand> brandList = ygBrandService.findByIdList(brandIdList);
            Map<Long, List<YgBrand>> listMap = brandList.stream().collect(Collectors.groupingBy(YgBrand::getId));
            ygCouponModels.stream().filter(coupon -> SceneType.Brand.equals(coupon.getSceneType())).forEach(coupon -> {
                List<Long> relateIdList = coupon.getRelateIdList();
                if (listMap.containsKey(relateIdList.get(0))) {
                    YgBrand ygBrand = listMap.get(relateIdList.get(0)).get(0);
                    coupon.setBrandId(ygBrand.getId());
                    coupon.setBrandName(ygBrand.getBrandName());
                }
            });
        }
    }

    @Override
    public List<YgCouponModel> findCouponListForPay(Long userId, BigDecimal productPrice, CouponStatus cStatus, Boolean useCoupon, Boolean onlySpecial,
                                                    String productIds, SalesPlatform salesPlatform) {
        if (!useCoupon) {
            cStatus = CouponStatus.Mutex;
        }
        List<YgCouponModel> coupon = ygCouponMapper.selectCouponListForPay(userId, productPrice, cStatus.name(), DateConvertUtils.format(new Date()),
                onlySpecial);
        for (YgCouponModel model : coupon) {
            long currentDate = DateConvertUtils.getDateStart(new Date()).getTime();
            long startDate = model.getStartDate().getTime();
            long endDate = model.getEndDate().getTime();
            if (useCoupon) {
                // 可用的
                if (currentDate - startDate >= 0 && endDate - currentDate >= 0 && productPrice.compareTo(model.getLimitPrice()) >= 0) {
                    // 但特例品不可以使用任何优惠券
                    if (onlySpecial) {
                        model.setCouponStatus(CouponStatus.Dissatisfy);
                    } else {
                        model.setCouponStatus(CouponStatus.Usable);
                    }
                }
                // 未开始
                else if (currentDate - startDate < 0 && productPrice.compareTo(model.getLimitPrice()) >= 0) {
                    model.setCouponStatus(CouponStatus.UnStart);
                }
                // 不满足条件
                else if (currentDate - startDate >= 0 && endDate - currentDate >= 0 && productPrice.compareTo(model.getLimitPrice()) < 0) {
                    model.setCouponStatus(CouponStatus.Dissatisfy);
                }
                // 过期
                else {
                    model.setCouponStatus(CouponStatus.InValid);
                }
            } else {
                // 与其他活动冲突，导致不可用
                model.setCouponStatus(CouponStatus.Mutex);
            }
            model.setIsFullCourt(Boolean.TRUE);
        }
        coupon.addAll(findCouponListForPay(userId, productIds, cStatus, useCoupon, onlySpecial, salesPlatform));
        if (cStatus.equals(CouponStatus.Usable)) {
            Collections.sort(coupon, (o1, o2) -> o2.getFaceValue().compareTo(o1.getFaceValue()));
        } else {
            Collections.sort(coupon, (o1, o2) -> o2.getCouponDetailId().compareTo(o1.getCouponDetailId()));
        }
        return coupon;
    }

    private List<YgCouponModel> findCouponForProduct(Long userId, Long couponDetailId, Date currentDate, CouponStatus couponStatus,
                                                     SalesPlatform salesPlatform) {
        List<YgCouponModel> ygCouponModels = ygCouponMapper.selectCouponForProduct(userId, couponDetailId, DateConvertUtils.format(currentDate), couponStatus == null ? null : couponStatus.name(),
                salesPlatform == null ? null : salesPlatform.name());
        setBrandInfo(ygCouponModels);
        return ygCouponModels;
    }

    private List<YgCouponModel> findCouponListForPay(Long userId, String productIds, CouponStatus useStatus, Boolean useCoupon, Boolean onlySpecial,
                                                     SalesPlatform salesPlatform) {
        List<YgCouponModel> modelList = this.findCouponForProduct(userId, null, new Date(), CouponStatus.Received, salesPlatform);
        if (CollectionUtils.isEmpty(modelList)) {
            return new ArrayList<>();
        }
        Iterator<YgCouponModel> iterator = modelList.iterator();
        while (iterator.hasNext()) {
            YgCouponModel model = iterator.next();
            long currentDate = DateConvertUtils.getDateStart(new Date()).getTime();
            long startDate = model.getStartDate().getTime();
            long endDate = model.getEndDate().getTime();
            CouponStatus flag = CouponStatus.UnUsable;
            if (!useCoupon) {
                model.setCouponStatus(CouponStatus.Mutex);
            } else if (endDate - currentDate < 0) {
                model.setCouponStatus(CouponStatus.InValid);
            } else if (currentDate - startDate < 0) {
                model.setCouponStatus(CouponStatus.UnStart);
            } else if (validateContainProductId(model.getProductIds(), productIds)) {
                model.setCouponStatus(CouponStatus.Usable);
                flag = CouponStatus.Usable;
            } else {
                model.setCouponStatus(CouponStatus.Mutex);
            }
            if (useStatus.equals(flag)) {
                continue;
            }
            iterator.remove();
        }
        return modelList;
    }

    private boolean validateContainProductId(String dbProductIds, String orderProductIds) {
        if (StringUtils.isBlank(dbProductIds) || StringUtils.isBlank(orderProductIds)) {
            return false;
        }
        List<String> dbList = Arrays.asList(dbProductIds.split(","));
        for (String idStr : Arrays.asList(orderProductIds.split("[,，]"))) {
            if (!dbList.contains(idStr)) {
                return false;
            }
        }
        return true;
    }

    @Override
    public int addCoupon(EditCouponReq editCouponReq) {

        if (!SceneType.ALL.equals(editCouponReq.getSceneType())) {
            Assert.notNull(editCouponReq.getProductIds(), "productIds can't be null");
        }

        YgCoupon ygCoupon = new YgCoupon();
        BeanUtils.copyProperties(editCouponReq, ygCoupon);
        ygCoupon.setCreateBy(editCouponReq.getHandler());
        ygCoupon.setCreateTime(editCouponReq.getUpdateTime());
        ygCoupon.setUpdateBy(editCouponReq.getHandler());
        this.save(ygCoupon);
        if (!SceneType.ALL.equals(editCouponReq.getSceneType())) {
            ygCouponMemberService.editCouponMember(ygCoupon.getId(), ygCoupon.getSceneType(), Arrays.asList(editCouponReq.getProductIds()), ygCoupon.getCreateBy());
        }
        return 1;

    }

    public int save(YgCoupon ygCoupon) {
        int row = ygCouponMapper.insertSelective(ygCoupon);
        if (row > 0) {
            if (ygCoupon.getCouponType().equals(CouponType.Postpone)) {
                return row;
            }
            List<YgCouponDetail> detailList = new ArrayList<>();
            for (int i = 0; i < ygCoupon.getSendNum(); i++) {
                YgCouponDetail detail = new YgCouponDetail();
                detail.setCouponCode(YgStringUtils.getRandomString(12).toUpperCase());
                detail.setCouponBatchId(ygCoupon.getId());
                detail.setFaceValue(ygCoupon.getFaceValue());
                detail.setStartDate(ygCoupon.getStartDate());
                detail.setEndDate(ygCoupon.getEndDate());
                detail.setUseStatus(CouponStatus.Received);
                detailList.add(detail);
            }
            couponDetailService.addCouponDetailBatch(detailList);
        }

        return row;
    }

    public int update(YgCoupon ygCoupon) {
        return ygCouponMapper.updateByPrimaryKeySelective(ygCoupon);
    }

    public int saveOrUpdate(YgCoupon ygCoupon) {
        int r = 0;
        if (ygCoupon.getId() != null) {
            r = this.update(ygCoupon);
        } else {
            r = this.save(ygCoupon);
        }
        return r;
    }

    @Override
    public YgCoupon findByCouponCode(String couponCode, Long userId) {
        return ygCouponMapper.selectByCouponCode(couponCode, userId);
    }

    @Deprecated
    @Override
    public YgCouponModel findCouponForPay(Long userId, Long couponDetailId, BigDecimal productPrice, Boolean onlySpecial, List<Long> productIds,
                                          SalesPlatform salesPlatform) {
        YgCouponModel model = ygCouponMapper.selectCouponForPay(userId, couponDetailId, productPrice, DateConvertUtils.format(new Date()), onlySpecial);
        if (CollectionUtils.isNotEmpty(productIds)) {
            List<YgCouponModel> list = this.findCouponForProduct(userId, couponDetailId, CouponStatus.Received, productIds, salesPlatform);
            if (CollectionUtils.isNotEmpty(list)) {
                YgCouponModel couponModel = list.get(0);
                if (model == null || couponModel.getFaceValue().compareTo(model.getFaceValue()) > 0) {
                    return couponModel;
                }
            }
        }
        return model;
    }

    public List<YgCouponModel> findCouponForProduct(Long userId, Long couponDetailId, CouponStatus useStatus, List<Long> productIds,
                                                    SalesPlatform salesPlatform) {
        if (CollectionUtils.isEmpty(productIds)) {
            return new ArrayList<>();
        }
        List<YgCouponModel> dbList = this.findCouponForProduct(userId, couponDetailId, new Date(), useStatus, salesPlatform);
        if (CollectionUtils.isEmpty(dbList)) {
            return new ArrayList<>();
        }
        Iterator<YgCouponModel> iterator = dbList.iterator();
        while (iterator.hasNext()) {
            YgCouponModel model = iterator.next();
            List<Long> relateIdList = model.getRelateIdList();
            if (CollectionUtils.isEmpty(relateIdList)) {
                continue;
            }
            for (Long id : productIds) {
                if (!relateIdList.contains(id)) {
                    iterator.remove();
                    break;
                }
            }
        }
        return dbList;
    }

    @Override
    public Message validCoupon(String couponCode, Long userId) {

        YgCouponDetail detail = couponDetailService.findByCouponCode(couponCode, null);
        if (detail != null) {
            if (detail.getUserId() == null) {
                long currentDate = DateConvertUtils.getDateStart(new Date()).getTime();
                long endDate = detail.getEndDate().getTime();
                if (currentDate - endDate > 0) {
                    return Message.error(documentConstant.COUPON_IS_INVALID, null);
                } else {
                    List<YgCouponDetail> list = couponDetailService.findByCouponBatchId(detail.getCouponBatchId(), userId);
                    // 是否达到最大领取数量
                    if (detail.getCoupon().getLeadNum().intValue() > 0 && list.size() >= detail.getCoupon().getLeadNum()) {
                        return Message.error(documentConstant.COUPON_MAXIMUN_IS_REACHED, null);
                    } else {
                        return Message.success(detail);
                    }
                }

            } else {

                return Message.error(documentConstant.COUPON_IS_BINDED, null);
            }

        }
        return Message.error(documentConstant.COUPON_CODE_ERROR, null);
    }

    @Override
    public Message bindCoupon(String couponCode, YgUser user) {
        Message msg = this.validCoupon(couponCode, user.getId());
        if (msg.getType().equals(Message.Type.success)) {
            YgCouponDetail detail = (YgCouponDetail) msg.getExtra();
            detail.setUserId(user.getId());
            detail.setUserName(user.getUserName());
            detail.setLeadTime(new Date());
            detail.setUseStatus(CouponStatus.Received);
            couponDetailService.update(detail);
            msg.setContent(documentConstant.COUPON_BIND_SUCCESS);
            msg.setExtra(null);
        }
        return msg;
    }

    @Override
    public Message receiveCoupon(Long couponBatchId, YgUser user) {
        return couponDetailService.receiveCoupon(couponBatchId, user);
    }

    @Override
    public Message receiveCouponBatch(String couponBatchIds, YgUser user) {
        if (couponBatchIds.equals("") || couponBatchIds.equals("null")) {
            return Message.success(documentConstant.COUPON_CODE_ERROR, null);
        }
        try {
            String[] cbIds = couponBatchIds.split(",");
            List<YgCouponDetail> detailList = new ArrayList<>();
            Message errMsg = Message.success(null);
            for (String cBatchId : cbIds) {
                Message message = couponDetailService.receiveCoupon(Long.parseLong(cBatchId), user);
                if (Message.isSuccess(message)) {
                    YgCouponDetail detail = (YgCouponDetail) message.getExtra();
                    detailList.add(detail);
                } else {
                    errMsg = message;
                }
            }
            if (detailList.size() == 0) {
                return errMsg;
            }
            return Message.success(documentConstant.COUPON_RECEIVE_SUCCESS, detailList);
        } catch (Exception e) {
            return Message.error(documentConstant.COUPON_CODE_ERROR, null);
        }

    }

    @Override
    public Message receiveCouponBatchV2(String couponBatchIds, Date endDate, YgUser user) {
        if (couponBatchIds.equals("") || couponBatchIds.equals("null")) {
            return Message.success(documentConstant.COUPON_CODE_ERROR, null);
        }
        try {
            String[] cbIds = couponBatchIds.split(",");
            List<YgCouponDetail> detailList = new ArrayList<>();
            for (String cBatchId : cbIds) {
                Message message = couponDetailService.receiveCoupon(Long.parseLong(cBatchId), endDate, user);
                if (Message.isSuccess(message)) {
                    YgCouponDetail detail = (YgCouponDetail) message.getExtra();
                    detailList.add(detail);
                }
            }
            return Message.success(documentConstant.COUPON_RECEIVE_SUCCESS, detailList);
        } catch (Exception e) {
            return Message.error(documentConstant.COUPON_CODE_ERROR, null);
        }

    }

    @Override
    public ResultSet<YgCoupon> search(QueryInfo queryInfo, Long supplierId, PromotionStatus pStatus, Date startDate, Date endDate, String q,
                                      CouponType couponType, Long[] batchIds) {
        List<YgCoupon> list = ygCouponMapper.selectSuper(queryInfo, supplierId, pStatus == null ? null : pStatus.name(), startDate, endDate, q, couponType,
                batchIds);
        int count = ygCouponMapper.countSuper(supplierId, pStatus == null ? null : pStatus.name(), startDate, endDate, q, couponType, batchIds);
        ResultSet<YgCoupon> resultSet = new ResultSet<YgCoupon>(count, list);
        return resultSet;
    }

    @Override
    public ResultSet<YgProduct4ListModel> findProductListByCouponId(Long id) {
        return findProductListByCouponId(id, SalesPlatform.Yiigoo);
    }

    @Override
    public ResultSet<YgProduct4ListModel> findProductListByCouponId(Long id, SalesPlatform salesPlatform) {
        List<YgProduct4ListModel> modelList;
        YgCoupon ygCoupon = this.findById(id);
        if (ygCoupon != null && !SceneType.ALL.equals(ygCoupon.getSceneType())) {
            List<YgCouponMember> memberList = ygCouponMemberService.findMemberList(id, ygCoupon.getSceneType());
            List<Long> productIds = memberList.stream().map(YgCouponMember::getRelateId).collect(Collectors.toList());
            modelList = ygProductService.findProduct4ListModelByIds(null, productIds, salesPlatform);
        } else {
            modelList = new ArrayList<>();
        }
        return new ResultSet<>(modelList.size(), modelList);
    }

    @Override
    public YgCouponModel findCouponForPayV2(Long userId, Long couponDetailId, BigDecimal productPrice,
                                            Boolean onlySpecial, List<YgShoppingCarModel> carList,
                                            SalesPlatform salesPlatform) {
        List<YgCouponModel> list = findCouponListForPayV2(userId, couponDetailId, productPrice,
                CouponStatus.Usable, Boolean.TRUE, onlySpecial, carList, salesPlatform);
        return CollectionUtils.isEmpty(list) ? null : list.get(0);
    }

    @Override
    public List<YgCouponModel> findCouponListForPayV2(Long userId, Long couponDetailId, BigDecimal productPrice,
                                                      CouponStatus couponStatus, Boolean useCoupon, Boolean onlySpecial,
                                                      List<YgShoppingCarModel> carList, SalesPlatform salesPlatform) {
        if (couponStatus.equals(CouponStatus.Usable) && (!useCoupon || onlySpecial)) {
            return null;
        }
        List<YgCouponModel> modelList = ygCouponMapper.selectCouponForProduct(userId, couponDetailId, null,
                CouponStatus.Received.name(), salesPlatform == null ? null : salesPlatform.name());
        if (CollectionUtils.isEmpty(modelList)) {
            return new ArrayList<>();
        }
        Iterator<YgCouponModel> iterator = modelList.iterator();
        while (iterator.hasNext()) {
            YgCouponModel model = iterator.next();
            CouponStatus flag = CouponStatus.UnUsable;
            if (!useCoupon || onlySpecial) {
                model.setCouponStatus(CouponStatus.Mutex);
            } else if (model.getStartDate().after(new Date())) {
                model.setCouponStatus(CouponStatus.UnStart);
            } else if (productPrice.compareTo(model.getLimitPrice()) < 0) {
                model.setCouponStatus(CouponStatus.Dissatisfy);
            } else if (model.getSceneType().equals(SceneType.ALL)) { // 全场券
                model.setCouponStatus(CouponStatus.Usable);
                flag = CouponStatus.Usable;
            } else { // 特殊券（品牌券和商品券）
                flag = validSpecialCoupon(model, carList);
            }
            // 结算页不显示过期优惠券
            if (couponStatus.equals(flag)
                    && model.getEndDate().compareTo(DateConvertUtils.getDateStart(new Date())) >= 0) {
                continue;
            }
            iterator.remove();
        }
        if (CollectionUtils.isNotEmpty(modelList)) {
            modelList.forEach(coupon -> {
                if (coupon.getFaceValue().compareTo(productPrice) > 0) {
                    coupon.setFaceValue(productPrice);
                }
            });
            if (CouponStatus.UnUsable.equals(couponStatus)) {
                modelList.sort((o1, o2) -> o2.getEndDate().compareTo(o1.getEndDate()));
            }
        }
        return modelList;
    }

    /**
     * 品牌券和商品券 检验
     *
     * @param model
     * @param carList
     */
    private CouponStatus validSpecialCoupon(YgCouponModel model, List<YgShoppingCarModel> carList) {
        List<Long> ids = model.getRelateIdList();
        // 过滤出符合券的商品
        List<YgShoppingCarModel> collect = carList.stream().filter(carModel -> {
            if (carModel.getIsSpecial()) {
                return false;
            }
            return (SceneType.Brand.equals(model.getSceneType()) && ids.contains(carModel.getBrandId().toString()))
                    || (SceneType.Product.equals(model.getSceneType()) && ids.contains(carModel.getProductId().toString()));
        }).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(collect)) {
            // 无商品符合条件
            model.setCouponStatus(CouponStatus.Mutex);
            return CouponStatus.UnUsable;
        }
        if (model.getLimitPrice() == null || model.getLimitPrice().compareTo(BigDecimal.ZERO) == 0) {
            // 无限制金额
            model.setCouponStatus(CouponStatus.Usable);
            return CouponStatus.Usable;
        }
        CarPackPriceResult packPriceResult = shoppingCarHandler.getPackAndNewCustomDisAndSpecialPrice(collect);
        BigDecimal price = packPriceResult.getProductPrice().subtract(packPriceResult.getSpecialPrice())
                .subtract(packPriceResult.getPackDisPrice()).subtract(packPriceResult.getNewCustomDisPrice());
        logger.info("validSpecialCoupon.CarPackPriceResult= 【{}】", JSON.toJSONString(packPriceResult));
//        if (SalesPlatform.Yiigoo.equals(model.getSalesPlatform())) {
//            price = price.subtract(packPriceResult.getVipDisPrice());
//        }
        if (price.compareTo(model.getLimitPrice()) < 0) {
            model.setCouponStatus(CouponStatus.Dissatisfy);
            return CouponStatus.UnUsable;
        }
        model.setCouponStatus(CouponStatus.Usable);
        return CouponStatus.Usable;
    }

    @Override
    public boolean validateUsable(SceneType couponSceneType, String couponProductIds, String paidProductIds) {
        try {
            switch (couponSceneType) {
                case ALL:
                    return true;
                case Product:
                    return validateContainProductId(couponProductIds, paidProductIds);
                case Brand:
                    Long[] convert = (Long[]) ConvertUtils.convert(paidProductIds.split(","), Long.class);
                    List<YgProduct> productList = ygProductService.findByIds(convert);
                    Map<Long, List<YgProduct>> collect = productList.stream().collect(Collectors.groupingBy(YgProduct::getBrandId));
                    if (collect.size() == 1 && collect.containsKey(Long.valueOf(couponProductIds))) {
                        return true;
                    }
                default:
                    break;
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public List<YgCouponModel> findCouponList(Boolean showWeb, SalesPlatform salesPlatform, Long productId, Long brandId) {
        List<YgCoupon> list = ygCouponMapper.findCouponListByProductId(showWeb, salesPlatform, productId, DateConvertUtils.format(new Date()));
        if (list != null && list.size() > 0) {
            List<YgCouponModel> couponModels = new ArrayList<YgCouponModel>();

            for (YgCoupon m : list) {
                if (m.getPostponeDays() != null && m.getPostponeDays() > 0) {
                    m.setStartDate(new Date());
                    Calendar ca = Calendar.getInstance();
                    ca.add(Calendar.DATE, Integer.valueOf(m.getPostponeDays().toString()));
                    m.setEndDate(ca.getTime());
                }
                if (m.getSceneType().equals(SceneType.Brand) && m.getRelateIdList().contains(brandId)) {
                    couponModels.add(getCouponModel(m));
                } else if (m.getSceneType().equals(SceneType.Product) && m.getRelateIdList().contains(productId)) {
                    couponModels.add(getCouponModel(m));
                } else {
                    couponModels.add(getCouponModel(m));
                }

            }
            return couponModels;
        }
        return null;

    }

    private YgCouponModel getCouponModel(YgCoupon m) {
        YgCouponModel mm = new YgCouponModel();
        mm.setCouponId(m.getId());
        mm.setLimitPrice(m.getLimitPrice());
        mm.setFaceValue(m.getFaceValue());
        mm.setStartDate(m.getStartDate());
        mm.setEndDate(m.getEndDate());
        mm.setSceneType(m.getSceneType());
        mm.setRelateIdList(m.getRelateIdList());
        return mm;
    }

    @Override
    public YgCouponPageModel getCouponPage() {
        String str = redisDao.get("CouponPage");
        if (StringUtils.isNotBlank(str)) {
            return JSONObject.parseObject(str, YgCouponPageModel.class);
        }
        return null;
    }

    @Override
    public YgCoupon findByDetailId(Long couponDetailId) {
        return ygCouponMapper.selectByDetailId(couponDetailId);
    }
}
